package com.binest.register.service.impl;


import com.binest.register.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

/**
 * @ClassName: MailServiceImpl
 * @Description:
 * @Author
 * @Date 2023/12/15
 * @Version 1.0
 */
@Component
public class MailServiceImpl implements IMailService {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.from}")
    private String from;
    @Value("${spring.mail.nickname}")
    private String nickname;
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        InternetAddress internetAddress =null;
        try {
            internetAddress = new InternetAddress(from,nickname,"gb2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            mimeMessageHelper.setFrom(internetAddress);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);
            mailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendSimpleMail(String to, String subject, String content, String... cc) {
        InternetAddress internetAddress =null;

        try {
            internetAddress = new InternetAddress(from,nickname,"gb2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            mimeMessageHelper.setFrom(internetAddress);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setCc(cc);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);
            mailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
